<template>
  <div class="flowpath-container">
    <div>
      <div class="mb20">
        <span class="color_494949 ft12 pr5">{{ translate('关键字') }}：</span>
        <el-input
          v-model="searchInfo"
          class="w164 mr10"
          :placeholder="translate('请输入关键字')"
        />
        <el-button class="settingBtn mr10" type="primary" @click="getList">
          {{ translate('查询') }}
        </el-button>
      </div>
      <div class="add">
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
          plain
        >
          {{ translate('新增') }}
        </el-button>
      </div>
      <el-table :border="true" :data="tableData">
        <!-- <el-table-column label="序号" type="index" width="80" /> -->
        <el-table-column
          :label="translate('合同名称')"
          prop="ContractName"
          width="auto"
        />
        <el-table-column :label="translate('合同编码')" prop="ContractCode" />
        <el-table-column :label="translate('合同金额')" prop="ContractMoney" />
        <el-table-column
          :label="translate('合同委托单位')"
          prop="ContractEntrustingUnit"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('合同起草日期')"
          prop="ContractDraftDate"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('供货单位')"
          prop="ProjectName"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('项目名称')"
          prop="InComeDate"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('合同状态')">
          <template #default="{ row }">
            <div>
              {{
                row.ContractState == '1'
                  ? translate('进行中')
                  : row.ContractState == '2'
                  ? translate('未生效')
                  : translate('已结束')
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('是否启用')">
          <template #default="{ row }">
            <div>
              {{ row.Enabled == 1 ? translate('是') : translate('否') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('操作')" width="350">
          <template #default="{ row }">
            <el-button
              v-if="MenuAuths('add')"
              plain
              size="small"
              type="primary"
              @click="uploadFn(row)"
            >
              {{ translate('上传附件') }}
            </el-button>
            <el-button
              v-if="MenuAuths('add')"
              plain
              size="small"
              type="primary"
              @click="downloadFn(row)"
            >
              {{ translate('查看附件') }}
            </el-button>
            <el-button
              v-if="MenuAuths('detail')"
              plain
              size="small"
              type="primary"
              @click="detailFn(row)"
            >
              {{ translate('详情') }}
            </el-button>
            <el-button
              v-if="MenuAuths('delete')"
              plain
              size="small"
              type="danger"
              @click="deleteFn(row)"
            >
              {{ translate('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="total > 0" class="pagination">
        <el-pagination
          background
          :current-page="pageNo"
          :layout="layout"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="1000px"
      @close="dialogVisible = false"
    >
      <detail :form="form" @deletedchild="deletedchild" />
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="submitFnDetail">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisiblefj"
      :title="translate('附件上传')"
      width="800px"
      @close="dialogVisiblefj = false"
    >
      <el-scrollbar
        wrap-class="scrollbar-wrapper"
        wrap-style="overflow-y: auto;"
      >
        <div class="file-div">
          <el-upload
            ref="upload"
            :action="action"
            :auto-upload="false"
            :before-remove="beforeRemove"
            :before-upload="beforeUpload"
            class="upload-demo"
            drag
            :file-list="fileList"
            :headers="headers"
            list-type="picture"
            multiple
            name="fileInput"
            :on-error="uploadError"
            :on-exceed="handleExceed"
            :on-preview="handlePreview"
            :on-success="handleSuccess"
          >
            <template #trigger>
              <vab-icon
                class="add-line"
                icon="add-line"
                style="font-size: 48px"
              />
            </template>
            <el-dialog
              v-model="dialogVisibleImg"
              append-to-body
              :title="translate('查看大图')"
            >
              <div>
                <el-image :src="dialogImageUrl" />
              </div>
            </el-dialog>
          </el-upload>
        </div>
      </el-scrollbar>
      <template #footer>
        <el-button @click="dialogVisiblefj = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="sumbitfn">
          {{ translate('上传') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisibleDown"
      :title="translate('附件下载')"
      width="800px"
      @close="dialogVisibleDown = false"
    >
      <el-scrollbar
        v-if="list.length > 0"
        wrap-class="scrollbar-wrapper"
        wrap-style="overflow-y: auto;"
      >
        <div class="file-div">
          <div
            v-for="(item, index) in list"
            :key="index"
            class="down-img"
            :class="item.isHover ? 'hover' : ''"
            @mouseleave="onLeave(item, index)"
            @mouseover="onHover(item, index)"
          >
            <img
              v-if="item.isImage"
              class="el-upload-list__item-thumbnail"
              :src="item.filePath"
            />
            <img
              v-else
              class="el-upload-list__item-thumbnail"
              :src="require('@/assets/fj.png')"
            />
            <div v-if="item.isHover" class="hover-icon">
              <span
                v-if="item.isImage"
                class="down-img-icon"
                @click="handlePictureCardPreview(item)"
              >
                <vab-icon
                  icon="add-circle-line"
                  style="font-size: 24px; color: #ffffff"
                />
              </span>
              <span class="down-img-icon" @click="handleDownload(item)">
                <vab-icon
                  icon="arrow-down-circle-line"
                  style="font-size: 24px; color: #ffffff"
                />
              </span>
              <span class="down-img-icon" @click="handleRemoveImg(item)">
                <vab-icon
                  icon="delete-bin-line"
                  style="font-size: 24px; color: #ffffff"
                />
              </span>
            </div>
            <div class="agreeTitle">{{ item.fileName }}</div>
          </div>
          <el-dialog v-model="dialogVisibleImg" width="800px">
            <el-scrollbar
              wrap-class="scrollbar-wrapper"
              wrap-style="overflow-y: auto;"
            >
              <div style="height: 800px">
                <el-image :src="dialogImageUrl" />
              </div>
            </el-scrollbar>
          </el-dialog>
        </div>
      </el-scrollbar>
      <div v-else class="noData">{{ translate('暂无附件') }}</div>
      <template #footer>
        <el-button @click="dialogVisibleDown = false">
          {{ translate('取消') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {
    agreePageData,
    agreeDelc,
    addAgreements,
    WF_DocumentList,
    WF_Documentdeldoc,
  } from '@/api/form'
  import detail from './components/detail'
  import { useUserStore } from '@/store/modules/user'
  import { MenuAuth } from '~/src/utils/permission'
  import { baseURL } from '@/config'
  import { translate } from '@/i18n'
  const { token } = useUserStore()
  export default defineComponent({
    name: 'Agreements',
    components: { detail },
    data() {
      return {
        fileList: [],
        tableData: [],
        list: [],
        searchInfo: '',
        action: '',
        tableRef: null,
        total: 0,
        pageNo: 1,
        pageSize: 20,
        dialogVisible: false,
        dialogVisiblefj: false,
        dialogVisibleImg: false,
        dialogVisibleDown: false,
        DetailPageData: {},
        headers: {},
        submitType: 'add',
        title: '新增合同',
        layout: 'total, sizes, prev, pager, next, jumper',
        deleList: [],
        cid: '',
        numberList: '',
        dialogImageUrl: '',
        MenuAuths: '',
        form: {
          ContractCode: '', //合同编码
          ContractName: '', //合同名称
          ContractMoney: '', //合同金额
          ContractEntrustingUnit: '', // 合同委托单位
          ContractDraftDate: '', //合同起草日期
          ContractBilling: '', //开票要求
          ContractPayment: '', // 汇款要求
          ContractType: '', // 合同类型
          ContractRequirement: '', //合同要求
          ContractDescribe: '', // 简介
          ContractSocialResults: '', // 合同社会效应
          ContractDeliver: '', // 合同交付
          ContractSecrecy: '', // 合同保密
          ContractRisk: '', // 合同风险
          CreateUserPhone: '', //创建人电话
          ProjectID: '', // 项目主键
          ProjectCode: '', // 项目编码
          ProjectName: '', // 项目名称
          OwnerId: '', // 归属主键
          OwnerName: '', // 归属名称
          OwnerType: '', // 归属类型
          ContractState: '2', // 合同状态
          Remark: '', // 备注
          Enabled: 0, // 是否启用
        },
      }
    },
    watch: {
      dialogVisiblefj(val) {
        if (!val) {
          this.$refs.upload.clearFiles()
        }
      },
    },
    created() {
      this.MenuAuths = MenuAuth
      this.getList()
    },
    methods: {
      translate(row) {
        return translate(row)
      },
      onHover(item, index) {
        this.list[index].isHover = true
      },
      onLeave(item, index) {
        this.list[index].isHover = false
      },
      async uploadFn(row) {
        this.dialogVisiblefj = true
        this.headers = this.headers = {
          Authorization: `Bearer ${token}`,
        }
        this.action = `${baseURL}/WF_Document/UploadFile?TypeName=W_Contract&FormId=${row.UniqueCode}`
      },
      downloadFn(row) {
        this.WF_DocumentList(row)
      },
      handlePictureCardPreview(row) {
        this.dialogVisibleImg = true
        this.dialogImageUrl = row.filePath
      },
      handleSuccess(file, fileList) {
        console.log(file, fileList)
        if (file.code != '200') {
          this.$message.warning(file.message)
        } else {
          this.$message.success('上传成功')
          this.dialogVisiblefj = false
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      beforeUpload(file, fileList) {
        console.log(file, fileList)
      },
      handleDownload(row) {
        window.open(row.filePath)
      },
      handleRemoveImg(item) {
        this.WF_Documentdeldoc(item)
      },
      async WF_Documentdeldoc(item) {
        const params = {
          fileId: item.fileId,
        }
        const data = await WF_Documentdeldoc(params)
        if (data.code == '200') {
          this.$message.success('删除成功')
          this.WF_DocumentList(item)
        }
      },
      handlePreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisibleImg = true
      },
      uploadError(file) {
        console.log(file)
        this.$message.warning('上传失败')
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
        )
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
      sumbitfn() {
        this.$refs.upload.submit()
        // this.dialogVisiblefj = false
        // this.$refs.upload.clearFiles()
      },
      async WF_DocumentList(row) {
        const params = {
          formId: row.UniqueCode || row.formId,
        }
        const data = await WF_DocumentList(params)
        if (data.code == '200') {
          if (data.data.data && data.data.data.length > 0) {
            data.data.data.map((item) => {
              item.isImage = this.isAssetTypeAnImage(item.fileExtensions)
            })
          }
          this.list = data.data.data
          this.dialogVisibleDown = true
        }
      },

      isAssetTypeAnImage(ext) {
        return (
          [
            '.png',
            '.jpg',
            '.jpeg',
            '.bmp',
            '.gif',
            '.webp',
            '.psd',
            '.svg',
            '.tiff',
          ].indexOf(ext.toLowerCase()) !== -1
        )
      },
      async getList() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: JSON.stringify([
            { name: 'FullName', value: this.searchInfo, displayType: 'like' },
          ]),
          export: false,
          value: '',
        }
        const data = await agreePageData(params)
        this.tableData = data.data.rows
        this.total = data.data.total
        console.log(this.tableData)
      },
      deletedchild(e) {
        this.deleList = e
        console.log(e)
      },
      deleteFn(row) {
        this.$confirm('确认删除该文件吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.deleted(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      async deleted(row) {
        const params = {
          cid: row.CID,
        }
        const data = await agreeDelc(params)
        if (data.code == '200') {
          this.$message({
            message: translate('删除成功'),
            type: 'success',
          })
          await this.getList()
        }
      },
      //分页条数切换
      handleSizeChange(val) {
        this.pageSize = val
        this.getList()
      },
      //分页切换
      handleCurrentChange(val) {
        this.pageNo = val
        this.getList()
      },
      addFn() {
          this.cid = ''
          this.submitType = 'add'
          this.title = translate('新增合同')
          this.form = {
          ContractCode: '', //合同编码
          ContractName: '', //合同名称
          ContractMoney: '', //合同金额
          ContractEntrustingUnit: '', // 合同委托单位
          ContractDraftDate: '', //合同起草日期
          ContractBilling: '', //开票要求
          ContractPayment: '', // 汇款要求
          ContractType: '', // 合同类型
          ContractRequirement: '', //合同要求
          ContractDescribe: '', // 简介
          ContractSocialResults: '', // 合同社会效应
          ContractDeliver: '', // 合同交付
          ContractSecrecy: '', // 合同保密
          ContractRisk: '', // 合同风险
          CreateUserPhone: '', //创建人电话
          ContractState: '2', // 合同状态
          Remark: '', // 备注
          Enabled: 0, // 是否启用
          ProjectCode: '', // 项目编码
          ProjectName: '', // 项目名称
        }
        this.dialogVisible = true
      },
      submitFnDetail() {
        this.AddData()
      },
      async detailFn(row) {
        this.form = row
        this.cid = row.CID
        this.submitType = 'edit'
        this.title = translate('查看合同')
        this.dialogVisible = true
      },
      async AddData() {
        const params = this.form
        if (this.cid) {
          params.CID = this.cid
        } else {
          const numberList = await this.getRandom()
          params.UniqueCode = numberList.toUpperCase()
        }
        const data = await addAgreements(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
      },
      S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      },
      async getRandom() {
        return `${
          this.S4() + this.S4()
        }-${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}${this.S4()}${this.S4()}`
      },
    },
  })
</script>
<style lang="scss" scoped>
  .flowpath-container {
    .color_494949 {
      color: #494949;
    }

    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }
    .add {
      margin-bottom: 10px;
      text-align: left;
    }
    .file-div {
      height: 300px;
    }
    ::v-deep .el-upload-dragger {
      height: 100%;
    }
    ::v-deep .ri-add-lin {
      font-size: 88px !important;
    }

    .down-img {
      position: relative;
      width: 100px;
      display: inline-block;
      padding: 0 10px;
      img {
        width: 100%;
        height: 100px;
      }
    }

    .hover {
      cursor: pointer;
    }
    .hover-icon {
      width: 100px;
      height: 100px;
      line-height: 100px;
      background: rgba(0, 0, 0, 0.5);
      position: absolute;
      top: 0;

      .down-img-icon {
        display: inline-block;
        padding: 0 4px;
      }
    }
    .agreeTitle {
      height: 35px;
      text-overflow: -o-ellipsis-lastline;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }
</style>
